##
#   Project: gmediacatalog - Catalog your media to find them later
#    Author: Fabio Castelli <muflone@vbsimple.net>
# Copyright: 2010 Fabio Castelli
#   License: GPL-2+
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 2 of the License, or (at your option)
#  any later version.
# 
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
# 
# On Debian GNU/Linux systems, the full text of the GNU General Public License
# can be found in the file /usr/share/common-licenses/GPL-2.
##

PLUGIN_NAME = 'TAR'
PLUGIN_VERSION = '0.1'
PLUGIN_DESCRIPTION = 'TAR extraction filter'
PLUGIN_AUTHOR = 'Fabio Castelli'

import tarfile

from constants import *
from plugins import GMediaCatalogPlugin, register_plugin

class GMediaCatalogPlugin_TAR(GMediaCatalogPlugin):
  def __init__(self, name, version, description, author):
    "Module initialization"
    GMediaCatalogPlugin.__init__(self, name, version, description, author)
    self.logger('__init__("%s", "%s", "%s", "%s")' % (
      PLUGIN_NAME, PLUGIN_VERSION, PLUGIN_AUTHOR, PLUGIN_DESCRIPTION))
    self.connection = None
    self.active = True

  def on_uiready(self, ui, connection):
    self.connection = connection

  def on_terminate(self):
    self.connection = None

  def on_new_file(self, volume_id, folder_id, child, info, category_id):
    if child.is_native() and info.get_content_type() in (
      'application/x-tar',                            # .tar
      'application/x-compressed-tar',                 # .tar.gz
      'application/x-bzip-compressed-tar'             # .tar.bz2
    ):
      tar = tarfile.open(child.get_path(), 'r')
      # Add a new path for the tarfile
      tar_id = self.connection.add_path(
        volume_id, 
        child.get_uri().replace('%20', ' '),
        info.get_icon().get_names()
      )
      paths = {}
      ublanks = unicode('')
      # Cycle tar content
      for info in tar:
        name = info.name
        # Strip initial /
        if name.startswith('/'):
          name = name[1:]
        uri = '%s/%s' % (child.get_uri().replace('%20', ' '), name)
        print uri

        # Item is a directory?
        if info.isdir():
          # Add new directory and add it to paths list
          paths[name] = self.connection.add_path(volume_id, uri, '')

        if '/' in name:
          path, basename = name.rsplit('/', 1)
        else:
          path = ''
          basename = name
        # Add file
        self.connection.add_file(
          volume_id,                                  # Volume ID FK
          path and paths[path] or tar_id,             # Path ID FK
          unicode(basename),                          # File name
          info.size,                                  # Size
          info.isdir() and ITEM_PATH or ITEM_FILE,    # File Type
          ublanks,                                    # Content type
          ublanks,                                    # Icons list
          info.mtime,                                 # Modification time
          info.mtime,                                 # Access time
          info.mtime,                                 # Changed time
          unicode(info.uname),                        # User owner
          unicode(info.gname),                        # User group
          info.mode,                                  # Mode
          unicode(info.linkname),                     # Target
          0,                                          # Flags (hidden)
          ublanks,                                    # Description
          category_id,                                # Category ID FK
          0                                           # Extra info
        )

      tar.close()
      paths = None

plugin = GMediaCatalogPlugin_TAR(
  PLUGIN_NAME, PLUGIN_VERSION, PLUGIN_DESCRIPTION, 
  PLUGIN_AUTHOR)
register_plugin(PLUGIN_NAME, plugin)
